#pragma once 

#include<iostream>
#include<vector>
#include<pthread.h>
#include<string>
#include<cstdlib>
#include<unistd.h>
#include<semaphore.h>

using namespace std;

static const int defaultNum = 5;

template<class T>
class RingQueue
{
private:
    void P(sem_t& sem)
    {
        sem_wait(&sem);
    }

    void V(sem_t& sem)
    {
        sem_post(&sem);
    }

    void Lock(pthread_mutex_t mutex)
    {
        pthread_mutex_lock(&mutex);
    }

    void UnLock(pthread_mutex_t mutex)
    {
        pthread_mutex_unlock(&mutex);
    }

public:
    RingQueue(int cap = defaultNum)
        :_ringqueue(cap)
        ,_cap(cap)
        ,_c_step(0)
        ,_p_step(0)
    {
        sem_init(&_cdata_sem,0,0);//第二个参数为是否共享，第三个为信号量的数量
        sem_init(&_pspace_sem,0,cap);

        pthread_mutex_init(&_c_mutex,nullptr);
        pthread_mutex_init(&_p_mutex,nullptr);
    }

    void push(const T& in)
    {
        Lock(_p_mutex);
        //申请信号量
        P(_pspace_sem);
        _ringqueue[_p_step] = in;
        _p_step++;
        _p_step %= _cap;

        //释放信号量
        V(_cdata_sem);
        UnLock(_p_mutex);
    }

    void pop(T* out)
    {
        //申请信号量
        P(_cdata_sem);
        Lock(_c_mutex);
        *out = _ringqueue[_c_step];
        _c_step++;
        _c_step %= _cap;
        //释放信号量
        UnLock(_c_mutex);
        V(_pspace_sem);
        
    }


    ~RingQueue()
    {
        sem_destroy(&_cdata_sem);
        sem_destroy(&_pspace_sem);

        pthread_mutex_destroy(&_c_mutex);
        pthread_mutex_destroy(&_p_mutex);
    }

private:
    vector<T> _ringqueue;
    int _cap;

    int _c_step;//消费者下标
    int _p_step;//生产者下标

    sem_t _cdata_sem;//消费者数据信号量
    sem_t _pspace_sem;//生产者空余位置信号量

    pthread_mutex_t _c_mutex;
    pthread_mutex_t _p_mutex;

};